<?php

namespace app\common\logic;

use app\admin\model\Admin;
use app\common\library\exception\ApiException;
use app\common\library\MemberVo;
use app\common\model\CarModels;
use app\common\model\Collection;
use app\common\model\Member;
use app\common\model\Message;
use app\common\model\Service;
use app\common\model\ServiceImage;
use app\common\model\ServiceMainBusiness;
use app\common\model\ServiceShop;
use app\common\model\UsedCar;
use fast\Date;
use think\db\Query;
use think\Exception;
use think\Log;
use think\Queue;

class ServiceShopLogic extends BaseLogic
{
    public $model;

    public function assignModel()
    {
        $this->model          = new ServiceShop();
    }

    public function handleSearch(Query $query, array $params): Query
    {
//        if (isset($params['keywords']) && !empty($params['keywords'])) {
//            $whereOrRaw = "service_shop.name  LIKE '%{$params['keywords']}%' or models.name  LIKE '%{$params['keywords']}%'";
//            $query->whereOrRaw($whereOrRaw);
//        }
        if (isset($params['status']) && !empty($params['status'])) {
            $query->where('service_shop.status',$params['status']);
        }
        if (isset($params['is_del'])) {
            $query->where('service_shop.is_del',$params['is_del']);
        }
        if (isset($params['show']) && !empty($params['show'])) {
            $query->where('service_shop.show',$params['show']);
        }
        if (isset($params['keywords']) && !empty($params['keywords'])) {
            $query->where('service_shop.name','LIKE',"%{$params['keywords']}%");
        }
        if (isset($params['main_business']) && !empty($params['main_business'])) {
            $whereOrRaw = "FIND_IN_SET({$params['main_business']},main_business)";
            $query->where($whereOrRaw);
        }
        if (isset($params['city']) && !empty($params['city'])) {
            $query->where('service_shop.city','eq',$params['city']);
        }
        if (isset($params['service_type']) && !empty($params['service_type'])) {
            $query->where('service_shop.service_type','eq',$params['service_type']);
        }

        if (isset($params['sort']) && $params['sort'] == 2) { //我发布的
            $query->where('service_shop.member_id','eq',MemberVo::instance()->getMemberId());
        }

        if (isset($params['member_id']) && !empty($params['member_id'])) { //我发布的
            $query->where('service_shop.member_id','eq',$params['member_id']);
        }
        if (isset($params['type']) && !empty($params['type'])) {
            $query->where('service_shop.type','eq',$params['type']);
        }

        if (isset($params['shop_id']) && !empty($params['shop_id'])) {
            $query->where('service_shop.shop_id','eq',$params['shop_id']);
        }


        return $query;
    }

    /**
     * 列表
     * @param array $params
     */
    public function index($params)
    {
        $params['status'] = 1;//审核状态
        $params['is_del'] = 0;//是否删除
        $params['show'] = 1;//是否上架
        $params['with'] = ['province','city','districts','member'];
        $params['orderBy'] = 'distance';
        $params['orderType'] = 'asc';
        if (isset($params['sort'])){
            if ($params['sort'] == 1){ //最新上架
                $params['orderBy'] = 'service_shop.id';
                $params['orderType'] = 'desc';
            }elseif ($params['sort'] == 3){ //距离优先
                $params['orderBy'] = 'distance';
                $params['orderType'] = 'asc';
            }
        }
        if (isset($params['latitude']) && !empty($params['latitude'])){
            $params['field'] = "id,service_type,service_shop.phone,service_shop.name shop_name,main_business,service_shop.address,member_id,shop_id,service_shop.longitude,service_shop.latitude,cover_img,type,(6378.138 * 2 * asin(sqrt(pow(sin((service_shop.latitude * pi() / 180 - " . $params['latitude'] . " * pi() / 180) / 2),2) + cos(service_shop.latitude * pi() / 180) * cos(" . $params['latitude'] . " * pi() / 180) * pow(sin((service_shop.longitude * pi() / 180 - " . $params['longitude'] . " * pi() / 180) / 2),2))) * 1000) as distance";
        }else{
            if (isset($params['sorts']) && $params['sort'] == 3){
                $params['orderBy'] = 'distance';
                $params['orderType'] = 'asc';
            }
            $params['field'] = "id,service_type,phone,name shop_name,main_business,address,member_id,shop_id,longitude,latitude,cover_img,type";
        }
        return  $this->getPageList($params)->each(function (&$item) use ($params){
//            $item['address'] = $item['province']['name'].$item['city']['name'].$item['districts']['name'].$item['address'];
            $item['main_business'] = ServiceMainBusiness::where(['id'=>['in',$item['main_business']]])->column('name');
            $collection = Collection::get(['main_id'=>$item['id'],'service_type'=>$params['service_type'],'member_id'=>MemberVo::instance()->getMemberId()]);
            $item['is_collection'] = !empty($collection) ? 1 : 0;
            $item['collection_id'] = !empty($collection) ? intval($collection['id']) : 0;
            if (isset($params['latitude']) && !empty($params['latitude'])){
//                $item['distance'] = getDistance(['lat'=>$item['latitude'],'lng'=>$item['longitude'],'to'=>$params['latitude'].','.$params['longitude']]);//获取距离
//                $item['distance'] = '距您'. $item['distance'].'km';
                $item['distance'] = '';
            }else{
                $item['distance'] = '';
            }
            $item['edit'] = 0;
            $item['phone_arr'] = explode(',',$item['phone']);
            if (MemberVo::instance()->getShopId() > 0){ //处于商家端
                if ($item['type'] == 2 && $item['shop_id'] == MemberVo::instance()->getShopId()){
                    $item['edit'] = 1;
                }
            }else{//处于车主端
                if ($item['type'] == 1 && $item['member_id'] == MemberVo::instance()->getMemberId()){
                    $item['edit'] = 1;
                }
            }
            unset($item['shop'],$item['member'],$item['province'],$item['city'],$item['districts']);
            return $item;
        });
    }

    /**
     * 编辑/添加
     * @param $params
     * @return bool
     * @throws ApiException
     */
    public function edit($params)
    {
        try{
            $params['member_id'] = MemberVo::instance()->getMemberId();
            $shop_id = MemberVo::instance()->getShopId();
            $params['main_business'] = implode(',',$params['main_business']);
            $fields = 'id,service_type,status,name,phone,main_business,province,city,districts,address,longitude,latitude,detail,member_id,shop_id,cover_img,type';
            //获取行政信息
            $location = reverseGeocoding($params['latitude'],$params['longitude']);
            $amaps = getAmaps();
            $params['province'] = getNameByChar($amaps,$location->province)['id'];
            $params['city'] = getNameByChar($amaps,$location->city)['id'];
            $params['districts'] = getNameByChar($amaps,$location->district)['id'];
            //手机号格式处理
            if (isset($params['phone_arr'])){
                $params['phone'] =  implode(',',$params['phone_arr']); //多电话格式
            }
            if (isset($params['id']) && !empty($params['id'])){ //更新
                $params['status'] = 0;
                ServiceShop::update($params,['id'=>$params['id']],$fields);
                Message::create(['content'=>"商机店铺：{$params['name']}信息已被编辑,请及时查看并审核！"]);
                ServiceImage::where(['main_id'=>$params['id'],'service_type'=>$params['service_type']])->delete();
                if (!empty($params['images'])){
                    foreach ($params['images'] as $v){
                        ServiceImage::create(['main_id'=>$params['id'],'image'=>$v,'service_type'=>$params['service_type']]);
                    }
                }
            }else{ //添加
                $params['type'] = 1;
                if ($shop_id > 0){
                    $params['shop_id'] = $shop_id;
                    $params['type'] = 2;
                }
                $res = ServiceShop::create($params,$fields);
                Message::create(['content'=>"商机店铺：{$params['name']}已被创建,请及时查看并审核！"]);
                if (!empty($params['images'])){
                    foreach ($params['images'] as $v){
                        ServiceImage::create(['main_id'=>$res->id,'image'=>$v,'service_type'=>$params['service_type']]);
                    }

                }
            }
            $admins = Admin::where(['status'=>'normal','member_id'=>['gt',0]])->select();
            Log::info($params);
            foreach ($admins as $v){
                Queue::push(\app\job\Message::class,[
                    'member_id'=>$v['member_id'],
                    'template_id'=>config('wechat_gzh')['gzh_template']['gd_wait_audit'],
                    'data'=>[
                        'thing13'=>"待处理商机工单",
                        'phrase3'=> $shop_id>0 ? '商家':'车主',
                        'time4'=>date('Y-m-d H:i')
                    ]
                ],'message');
            }

            return true;
        }catch (Exception $e){
            throw new ApiException($e->getMessage(),404);
        }
    }

    /**
     * 获取主营列表
     * @param $params
     * @return false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function main_business($params)
    {
        return ServiceMainBusiness::field('id,name')->where(['service_type'=>$params['service_type'],'status'=>1,'is_del'=>0])->select();
    }



    /**
     * 获取车辆详情
     * @return ServiceShop|null
     * @throws ApiException
     * @throws \think\exception\DbException
     */
    public function car_detail($params)
    {
        $params['member_id'] = MemberVo::instance()->getMemberId();
        $info = UsedCar::get($params['id']);
        if (!$info)
            throw new ApiException('查无该车辆信息',404);
        $info['edit'] = 0;
        if ($info['member_id'] == MemberVo::instance()->getMemberId()){
            $info['edit'] = 1;
        }
        return $info;
    }

    /**
     * 商机详情
     * @return ServiceShop|null
     * @throws ApiException
     * @throws \think\exception\DbException
     */
    public function detail($params)
    {
        $params['member_id'] = MemberVo::instance()->getMemberId();
        $info = ServiceShop::get($params['id'],['province','city','districts']);
        if (!$info)
            throw new ApiException('查无该店铺信息',404);
        $info = $info->toArray();
        $info['edit'] = 0;//可编辑状态 0不能编辑 1可以编辑
        if (MemberVo::instance()->getShopId() > 0){ //处于商家端
            if ($info['shop_id'] == MemberVo::instance()->getShopId()){
                $info['edit'] = 1;
            }
        }else{
            if ($info['type'] == 1 && $info['member_id'] == MemberVo::instance()->getMemberId()){
                $info['edit'] = 1;
            }
        }
//        $info['address'] = $info['province']['name'].$info['city']['name'].$info['districts']['name'].$info['address'];
        $info['main_business'] = ServiceMainBusiness::where(['id'=>['in',$info['main_business']]])->column('name');
        $collection = Collection::get(['main_id'=>$info['id'],'service_type'=>$info['service_type'],'member_id'=>MemberVo::instance()->getMemberId()]);
        $info['is_collection'] = !empty($collection) ? 1 : 0;
        $info['collection_id'] = !empty($collection) ? intval($collection['id']) : 0;
        if (isset($params['latitude']) && !empty($params['latitude'])){
//            $info['distance'] = getDistance(['lat'=>$info['latitude'],'lng'=>$info['longitude'],'to'=>$params['latitude'].','.$params['longitude']]);//获取距离
            $info['distance'] = getStraightDistance($params['latitude'],$params['longitude'],$info['latitude'],$info['longitude']);//获取距离
            $info['distance'] = $info['distance'].'km';
        }else{
            $info['distance'] = '';
        }
        $info['phone_arr'] = explode(',',$info['phone']);
        $info['images'] = ServiceImage::where(['main_id'=>$info['id'],'service_type'=>$info['service_type']])->select()->column('image');
        unset($info['province'],$info['city'],$info['districts']);
        return $info;
    }

    /**
     * 商机信息
     * @return ServiceShop|null
     * @throws ApiException
     * @throws \think\exception\DbException
     */
    public function info($params)
    {
        $params['member_id'] = MemberVo::instance()->getMemberId();
        $info = ServiceShop::get($params['id'])->toArray();
        if (!$info)
            throw new ApiException('查无该店铺信息',404);
        if (MemberVo::instance()->getShopId() > 0){ //处于商家端
            if ($info['shop_id'] != MemberVo::instance()->getShopId()){
                throw new ApiException('无该店铺编辑权限',404);
            }
        }else{
            if ($info['member_id'] != MemberVo::instance()->getMemberId()){
                throw new ApiException('无该店铺编辑权限',404);
            }
        }
        $info['phone_arr'] = explode(',',$info['phone']);
        $info['service_name'] = Service::where('id',$info['service_type'])->value('name');
        $info['main_business'] = empty($info['main_business']) ? [] : explode(',',$info['main_business']);
        $info['images'] = ServiceImage::field('image url')->where(['main_id'=>$info['id'],'service_type'=>$info['service_type']])->select();
        return $info;
    }

    /**
     * 我的商机列表
     * @param array $params
     */
    public function my_service($params)
    {
        $params['is_del'] = 0;
        $params['with'] = ['province','city','districts','member'];
        $params['orderBy'] = 'service_shop.id';
        $params['orderType'] = 'desc';
        $params['field'] = "id,service_type,show,status,phone,name shop_name,main_business,address,member_id,shop_id,longitude,latitude,cover_img,type";
        return  $this->getPageList($params)->each(function (&$item) use ($params){
            $item['main_business'] = ServiceMainBusiness::where(['id'=>['in',$item['main_business']]])->column('name');
            $collection = Collection::get(['main_id'=>$item['id'],'service_type'=>$params['service_type'],'member_id'=>MemberVo::instance()->getMemberId()]);
            $item['is_collection'] = !empty($collection) ? 1 : 0;
            $item['collection_id'] = !empty($collection) ? intval($collection['id']) : 0;
            $item['edit'] = 1;
            unset($item['shop'],$item['member'],$item['province'],$item['city'],$item['districts']);
            return $item;
        });
    }


}